<template>
  <div style="width: 100%">
    <a-card>
      <a-form :form="form">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item
              label="培养方案模板名称"
            >
              <a-input v-decorator="['fambmc',
                {
                  rules: [{ required: true, message: '请填写培养方案模板名称!' }],
                }]" :disabled="isCompleteBase"/>
            </a-form-item>
          </a-col>
          <!-- <a-col :md="8" :sm="24">
            <a-form-item
              label="培养来源"
            >
              <a-select v-decorator="['xslx',
                {
                  rules: [{ required: true, message: '请选择培养来源!' }],
                }]" :disabled="isCompleteBase">
                <a-select-option v-for="i in TYPE0503" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->
          <a-col :md="8" :sm="24">
            <a-form-item
              label="培养模式"
            >
              <a-select v-decorator="['pymsm',
                {
                  rules: [{ required: true, message: '请选择培养模式!' }],
                }]"  :disabled="isCompleteBase" @change="e => handleChange(e)" >
                <a-select-option v-for="i in TYPE0347" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              label="培养类别"
            >
              <a-select v-decorator="['xslbm',
                {
                  rules: [{ required: true, message: '请选择培养类别!' }],
                }]" :disabled="isCompleteBase">
                <a-select-option v-for="i in TYPE0075" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row style="text-align: center" v-if="!isCompleteBase">
          <a-button type="primary" @click="completeBase">制定</a-button>
        </a-row>
      </a-form>
      <a-tabs defaultActiveKey="1" v-if="isCompleteBase">
        <a-tab-pane tab="课程设置" key="1">
          <course-set ref="course"/>
        </a-tab-pane>
        <a-tab-pane tab="培养过程" key="2" forceRender>
          <process-set ref="process"/>
        </a-tab-pane>
        <a-tab-pane tab="攻读学位学分要求" key="3" forceRender>
          <credit :pymsmc="pymsmc" :edit="false" ref="credit"/>
        </a-tab-pane>
        <a-tab-pane tab="适用范围设置" key="4" forceRender>
          <scope ref="scope" :baseValues="baseValues"/>
        </a-tab-pane>
      </a-tabs>
      <div class="ant-pro-footer-toolbar">
        <a-button style="float: right;margin: 10px;" @click="back">返回</a-button>
        <a-button style="float: right;margin-top: 10px;" @click="submit" :loading="loadingBtn" type="primary">保存</a-button>
      </div>
    </a-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import courseSet from './courseSet'
import credit from './credit'
import scope from './scope'
import processSet from './processSet'

export default {
  data () {
    return {
      form: this.$form.createForm(this),
      isCompleteBase: false,
      pymsmc: '',
      baseValues: '',
      loadingBtn: false
    }
  },
  components: {courseSet, credit, scope, processSet},
  computed: {
    ...mapState({
      TYPE0347: state => state.app['TYPE0347'],
      TYPE0503: state => state.app['TYPE0503'],
      TYPE0075: state => state.app['TYPE0075']
    })
  },
  created () {
    this.$store.dispatch('app/setDictionary', 'TYPE0347')
    this.$store.dispatch('app/setDictionary', 'TYPE0503')
    this.$store.dispatch('app/setDictionary', 'TYPE0075')
    if (this.$route.query.id) {
      this.$api.cultivate.templateDetail(this.$route.query.id).then(res => {
        let temData = res.data
        this.baseValues = temData.pyfamb
        this.pymsmc = temData.pyfamb.pymsmc
        this.isCompleteBase = true
        this.$nextTick(() => {
          this.form.setFieldsValue({
            fambmc: temData.pyfamb.fambmc,
            xslx: temData.pyfamb.xslx,
            pymsm: temData.pyfamb.pymsm,
            xslbm: temData.pyfamb.xslbm
          })
          this.$refs.course.kcList = temData.pyfambkcList.map(k => {
            return Object.assign(k, {
              kch: k.kcdm,
              zxs: k.xs
            })
          })
          this.$refs.process.kcList = temData.pyfambPkcList.map(k => {
            return Object.assign(k, {
              kch: k.kcdm,
              zxs: k.xs
            })
          })
          this.$refs.credit.form.setFieldsValue(temData.pyfamb)
          this.$refs.scope.pyfambfwList = temData.pyfambfwList
          this.$refs.scope.lyxkdm = (temData.pyfambfwList.length && temData.pyfambfwList[0].xkdm) ? temData.pyfambfwList[0].xkdm.split(',') : []
          this.$refs.scope.initSubjectList()
          if (temData.pyfamb.pymsm === '01' || temData.pyfamb.pymsm === '03') {
            this.$refs.scope.tableData = temData.pyfambfwList.map(f => {
              return Object.assign({}, f, {
                mlxkdm: {key: f.mlxkdm, label: f.mlxkmc},
                yjxkdm: f.xkdm.split(',').map((xk, index) => {
                  return {
                    key: xk,
                    label: f.xkmc.split(',')[index]
                  }
                })
              })
            })
          }
        })
      })
    }
  },
  methods: {
    completeBase () {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        this.baseValues = values
        this.isCompleteBase = true
        this.$nextTick(() => {
          this.$refs.scope.initSubjectList()
        })
      })
    },
    handleChange (e) {
      this.pymsmc = this.TYPE0347.find(arr => {
        return arr.code === e
      }).name
    },
    back () {
      this.$router.back()
    },
    async submit () {
      try {
        const addForm = new Promise((resolve, reject) => {
          this.form.validateFields((err, values) => {
            if (err) {
              reject(err)
              return
            }
            resolve(values)
          })
        })
        let {fambmc, xslx, pymsm, xslbm} = await addForm
        let kcList = this.$refs.course.kcList
        if (!kcList.length) {
          throw Error('请添加课程')
        }
        let pkcList = this.$refs.process.kcList
        if (!pkcList.length) {
          throw Error('请添加培养过程')
        }
        const creditForm = new Promise((resolve, reject) => {
          this.$refs.credit.form.validateFields((err, values) => {
            if (err) {
              reject(new Error('请完善攻读学位学分要求'))
              return
            }
            resolve(values)
          })
        })
        let pyfamb = await creditForm
        if (pyfamb.kczxf > pyfamb.kczgxf) {
          throw Error('课程最低学分不能高于课程最高学分')
        }
/*        let credit = this.$refs.credit
        if(credit.total > credit.form.getFieldValue('kczgxf') || credit.total < credit.form.getFieldValue('kczxf')){
          throw Error('课程学分设置只能在最低学分和最高学分之间')
          return
        }*/

        let pyfambfwList = []
        if (pymsm == '01' || pymsm == '03') { // 学士学位
          let scopeList = this.$refs.scope.tableData.filter(s => {
            return !s.editable
          })
          if (!scopeList.length) {
            throw Error('请完善适用范围设置')
          }
          pyfambfwList = scopeList.map(s => {
            return Object.assign({}, s, {
              mlxkdm: s.mlxkdm.key,
              xkdm: s.yjxkdm && s.yjxkdm.map(yjxk => {
                return yjxk.key
              }).join(','),
              xslb: xslbm
            })
          })
        }else{ // 专业学位
          const lyxkdm = this.$refs.scope.lyxkdm
          if (!lyxkdm.length) {
            throw Error('请完善适用范围设置')
          }
          pyfambfwList.push({
            xkdm: lyxkdm && lyxkdm.join(',')
          })
        }
        let params = {
          pyfamb: Object.assign({}, pyfamb, {xslx, pymsm, xslbm, fambmc}),
          pyfambfwList: pyfambfwList,
          pyfambkcList: kcList.map(k => {
            return {
              bxhxx: k.bxhxx,
              kcdm: k.kch,
              kclxm: k.kclxm,
              sfxwk: k.sfxwk,
              id: k.id
            }
          }),
          pyfambPkcList: pkcList.map(k => {
            return {
              bxhxx: k.bxhxx,
              kcdm: k.kch,
              kclxm: k.kclxm,
              sfxwk: k.sfxwk,
              id: k.id
            }
          })
        }
        this.loadingBtn = true
        let apiFn = this.$route.query.id ? 'templateUpdate' : 'templateAdd'
        if (this.$route.query.id) {
          params.pyfamb.id = this.$route.query.id
        }
        this.$api.cultivate[apiFn](params).then(res => {
          this.$message.success('操作成功')
          this.$router.back()
        }).finally(() => {
          this.loadingBtn = false
        })
      } catch (error) {
        error.message && this.$message.error(error.message)
      }
    }
  }
}
</script>

<style>

</style>
